﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PiaoanWeb.AppLogic.DataAccessLayer;
namespace PiaoanWeb.AppLogic.BusinessLogicLayer
{
    [System.ComponentModel.DataObject(true)]
    public class NewsBLL : IDisposable
    {
        DatabaseContext _DatabaseContext;
        public NewsBLL()
            : this(new DatabaseContext())
        {
        }

        public NewsBLL(DatabaseContext DatabaseContext)
        {
            _DatabaseContext = DatabaseContext;
        }

        public void Dispose()
        {
            if (_DatabaseContext != null)
            {
                _DatabaseContext.Dispose();
                _DatabaseContext = null;
            }

            GC.SuppressFinalize(this);
        }

        public List<News> GetAllNews()
        {
            return _DatabaseContext.News.Where(n => !n.IsDeleted).ToList();
        }

        public News GetNewsByID(int newsID)
        {
            return _DatabaseContext.News.Where(n => n.ID == newsID).FirstOrDefault();
        }

        public void AddNews(News news)
        {
            _DatabaseContext.News.Add(news);
            _DatabaseContext.SaveChanges();
        }

        public void Save()
        {
            _DatabaseContext.SaveChanges();
        }

        public void DeleteNewsByID(int newsID)
        {
            News news = _DatabaseContext.News.Where(n => n.ID == newsID).FirstOrDefault();
            _DatabaseContext.News.Remove(news);
            _DatabaseContext.SaveChanges();
        }

        public List<News> GetLatestNews()
        {
            return _DatabaseContext.News.Where(n => !n.IsDeleted).OrderByDescending(n=>n.ID).Take(8).ToList();
        }
    }
}